# -*- coding: utf-8 -*-
# from multiprocessing import Manager
#
# manager = Manager()
# _global_dict = manager.dict()
_global_dict = {}
MAX_DICT_NUM = 10000000
MAX_LIST_NUM = 10000000


def get_value_type(value):
    '''
    支持list和dict
    '''
    if type(value) == type({}):
        return 'dict'
    elif type(value) == type([]):
        return 'list'
    else:
        return None


def split_value_in_count(value, value_type):
    '''
    将value分成count份，list格式
    '''
    value_list = []
    if value_type == 'dict':
        t = 0
        vocab = value.keys()
        length = len(vocab)
        while t < length:
            d = {vocab[j]: value[vocab[j]] for j in xrange(t, t + MAX_DICT_NUM) if j < length}
            t += MAX_DICT_NUM
            value_list.append(d)
    elif value_type == 'list':
        t = 0
        length = len(value)
        while t < length:
            d = [value[j] for j in xrange(t, t + MAX_LIST_NUM) if j < length]
            t += MAX_LIST_NUM
            value_list.append(d)

    return value_list


def merge_value_in_count(key, value_type, count):
    if value_type == 'dict':
        value = {}
        for i in xrange(count):
            value.update(_global_dict[key + str(i)])
        return value
    elif value_type == 'list':
        value = []
        for i in xrange(count):
            value += _global_dict[key + str(i)]
        return value
    else:
        return None


def set_value(key, value):
    """ 定义一个全局变量 """
    value_type = get_value_type(value)
    MAX_NUM = MAX_LIST_NUM if value_type == 'list' else MAX_DICT_NUM
    if len(value) < MAX_NUM:
        _global_dict[key] = value
    else:
        count = (len(value) - 1) / MAX_NUM + 1
        _global_dict[key] = '###\t:\t'+ value_type + '\t:\t'+str(count)   # 分片存储
        values = split_value_in_count(value, value_type)
        for i in xrange(count):
            _global_dict[key + str(i)] = values[i]


def get_value(key, def_value=None):
    """ 获得一个全局变量,不存在则返回默认值 """
    global _global_dict

    try:
        value = _global_dict[key]
        if value.startswith('###\t:\t'):
            count = int(value.split('\t:\t')[2])
            value_type = value.split('\t:\t')[1]
            return merge_value_in_count(key, value_type, count)
        return value
    except:
        return def_value
